package cn.mengfly.fxtest.app;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Mengfly
 */
public class GetHtmlApp extends Application {

    private HBox bottomControls;
    private ProgressBar pb;
    private Label messageLabel;

    private TextField tfUrl;
    private TextArea contents;

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent p = createMainView();

        Scene scene = new Scene(p);
        primaryStage.setTitle("ProgressBarApp");
        primaryStage.setWidth( 667 );
        primaryStage.setHeight( 376 );
        primaryStage.setScene( scene );
        primaryStage.show();
    }

    private Parent createMainView() {
        VBox vBox = new VBox();
        vBox.setPadding(new Insets(10));
        vBox.setSpacing(10);

        HBox topControl = new HBox();
        topControl.setAlignment(Pos.CENTER_LEFT);
        topControl.setSpacing(4);

        Label label = new Label("URL");
        tfUrl = new TextField();
        HBox.setHgrow(tfUrl, Priority.ALWAYS);

        Button btnGetHtml = new Button("Get Html");
        btnGetHtml.setOnAction(this::getHtml);
        topControl.getChildren().addAll(label, tfUrl, btnGetHtml);

        contents = new TextArea();
        VBox.setVgrow(contents, Priority.ALWAYS);

        bottomControls = new HBox();
        bottomControls.setVisible(false);
        bottomControls.setSpacing(4);
        HBox.setMargin(bottomControls, new Insets(4));

        pb = new ProgressBar();
        messageLabel = new Label("");
        bottomControls.getChildren().addAll(pb, messageLabel);

        vBox.getChildren().addAll(topControl, contents, bottomControls);

        return vBox;
    }

    private void getHtml(ActionEvent actionEvent) {
        String url = tfUrl.getText();

        Task<String> task = new Task<String>() {
            @Override
            protected String call() throws Exception {
                updateMessage("Getting Html from " + url);
                updateProgress(0.5, 1);

                HttpURLConnection c = null;
                InputStream is = null;

                StringBuilder retval = new StringBuilder();

                try {
                    c = (HttpURLConnection) new URL(url).openConnection();
                    updateProgress(0.6, 1);
                    is = c.getInputStream();
                    int ch;
                    while ((ch = is.read()) != -1) {
                        retval.append((char)ch);
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (c != null) {
                        c.disconnect();
                    }
                }
                updateMessage("Html retrieved");
                updateProgress(1, 1);
                return  retval.toString();
            }

            @Override
            protected void succeeded() {
                contents.setText(getValue());
            }

            @Override
            protected void failed() {
                Alert alert = new Alert(AlertType.ERROR, getException().getMessage());
                alert.showAndWait();
            }
        };

        bottomControls.visibleProperty().bind(task.runningProperty());
        pb.progressProperty().bind(task.progressProperty());
        messageLabel.textProperty().bind(task.messageProperty());

        new Thread(task).start();
    }
}
